package main

import (
	"executeserver/src/worker"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func ServerHandleError(err error, when string) {
	if err != nil {
		fmt.Println(err, when)
		os.Exit(1)
	}
}

func main() {
	// var str = `{"host":"127.0.0.1","username":"root","password":"aa778899","database":"demo_mall","port":3306}`
	// model.GetMysqlConn(str)
	// var redisStr = `{"host":"127.0.0.1","port":6379,"password":"aa778899"}`
	// model.CreateRedis(redisStr)

	var b = worker.TestData1
	b.LeaderIP = "192.168.1.101"
	log.Println(worker.TestData1.LeaderIP, b.LeaderIP)
	worker.HandleReceiveTask(b)
	<-time.After(2 * time.Second)

	worker.HandleReceiveTask(worker.TestData1)

	<-time.After(2 * time.Second)
	go func() {
		log.Println("main go func running!!!")
		<-time.After(20 * time.Second)
		log.Println("延迟20S发送任务")
		worker.HandleReceiveTask(b)
		<-time.After(1 * time.Second)
		worker.HandleReceiveTask(worker.TestData1)
	}()
	worker.Run()

}
func LoadConfigFromYaml() error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		return err
	}
	// if err = viper.Unmarshal(&MyConfig); err != nil {
	// 	return err
	// }
	return nil
}

//监听配置文件的修改和变动
func WatchConfig() error {
	if err := LoadConfigFromYaml(); err != nil {
		return err
	}

	viper.WatchConfig()

	//监听回调函数
	watch := func(e fsnotify.Event) {
		log.Printf("Config file is changed: %s \n", e.String())
		// log.Println("port", viper.Get("mysql.port"))
		// LoadConfigFromYaml()
	}

	viper.OnConfigChange(watch)
	return nil
}
